import pandas as pd 
from collections import Counter
from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker
from pyecharts.globals import ThemeType
from pyecharts.charts import Pie
from pyecharts.charts import Bar, Timeline
from pyecharts.charts import Liquid
from pyecharts.charts import Geo
from pyecharts.globals import ChartType, SymbolType
from pyecharts.charts import TreeMap
from flask import Flask,render_template
from pyecharts.charts import Line
from pyecharts.charts import WordCloud



app= Flask(__name__)

@app.route('/')
def index():
    df_学校 = pd.read_csv('data/school.csv',encoding='gbk')
    df_专业 = pd.read_csv('data/professional.csv',encoding='gbk')
    return (df_学校,df_专业)

@app.route('/a')
def a():
    df_学校=index()[0]
    df_学校.drop_duplicates(inplace=True)
    各省份高校数量 = [i for i in df_学校['省份'].value_counts().items()]
    map = (
        Map(init_opts=opts.InitOpts(bg_color="white",  width="900px", height="700px"))
            .add("各省份高校数量", [list(i) for i in 各省份高校数量])
            .set_global_opts(
            title_opts=opts.TitleOpts("各省份高校数量"),
            visualmap_opts=opts.VisualMapOpts(
                is_piecewise=True,  
                pieces=[
                    {"min": 201, "label": '>200所', "color": "#FF4500"},
                    {"min": 161, "max": 200, "label": '161-200所', "color": "#2F4F4F"}, 
                    {"min": 121, "max": 160, "label": '121-160所', "color": "#008080"},
                    {"min": 81, "max": 120, "label": '81-120所', "color": "#5F9EA0"},
                    {"min": 41, "max": 80, "label": '41-80所', "color": "#AFEEEE"},
                    {"min": 0, "max": 40, "label": '0-40所', "color": "#E1FFFF"},
                ],
                range_text=['高', '低'],
            ),
        )
    )
    map.render('map.html')
    with open("map.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,a='active',wz=''
    )

@app.route('/b')
def b():
    df_学校=index()[0]
    df_学校.drop_duplicates(inplace=True)
    各省份高校数量 = [i for i in df_学校['省份'].value_counts().items()]
    data_pair =  [list(i) for i in 各省份高校数量]

    (
    Pie(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add(
        series_name="访问来源",
        data_pair=data_pair,
        radius=["30%", "75%"],
        center=["35%", "50%"],
        rosetype="radius",
        label_opts=opts.LabelOpts(is_show=False, position="center"),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="各省份高校数量",
            pos_left="center",
            pos_top="20",
            title_textstyle_opts=opts.TextStyleOpts(color="black"),
        ),
        legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%", orient="vertical"),
    )
    .set_series_opts(
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
        ),
        label_opts=opts.LabelOpts(color="black"),
    ).render('pie2.html'))
    with open("pie2.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,b='active',wz=''
    )

@app.route('/c')
def c():
    df_学校=index()[0]
    df_学校.drop_duplicates(inplace=True)
    水平 = [i for i in df_学校['水平层次'].value_counts().items()]
    c = (
     Pie(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add(
        "",
        [list(z) for z in 水平],
        radius=["40%", "75%"],
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="专科（高职）与本科数量占比"),
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
    .render("pie.html")
)
    with open("pie.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,c='active',wz=''
    )

@app.route('/d')
def d():
    df_学校=index()[0]
    df_学校.drop_duplicates(inplace=True)
    类型 = [i for i in df_学校['办学类型'].value_counts().items()]
    c = (
     Pie(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add(
        "",
        [list(z) for z in 类型],
        radius=["40%", "75%"],
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="办学类型：民办&公办（圆环图）"),
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
    .render("pie3.html")

)
    with open("pie3.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,d='active',wz=''
    )

@app.route('/e')
def e():
    df_学校=index()[0]
    df_学校.drop_duplicates(inplace=True)
    类别 = [i for i in df_学校['办学类别'].value_counts(ascending=True).items()]
    类 = []
    数量=[]
    for a in range(len(类别)):
        类.append(类别[a][0])
        数量.append(类别[a][1])
    c = (
    Line(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add_xaxis(xaxis_data=类)
    .add_yaxis(
        "类别数量",
        数量,
        symbol="triangle",
        symbol_size=20,
        linestyle_opts=opts.LineStyleOpts(color="green", width=4, type_="dashed"),
        itemstyle_opts=opts.ItemStyleOpts(
            border_width=3, border_color="yellow", color="blue"
        ),
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="高校办学类别占比"))
    .render("line.html")
)
    with open("line.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,e='active',wz=''
    )

@app.route('/f')
def f():
    df_专业=index()[1]
    特色=df_专业[df_专业['国家特色专业'].isin(['是'])].reset_index()
    学校_特色=[i for i in 特色['学校'].value_counts().items()]
    学校_特色_top10 = 学校_特色[0:10]
    data=[]
    for i in range(10):
        data.append({'value':学校_特色_top10[i][1],'name':学校_特色_top10[i][0]})
        data_pair =  [list(i) for i in 学校_特色_top10]

    c = (
    TreeMap(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add("学校", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="国家特色专业学校top10"))
    .render("tree1.html")
)
    with open("tree1.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,f='active',wz=''
    )

@app.route('/g')
def g():
    df_专业 =index()[1]
    专业=[i for i in df_专业['专业名称'].value_counts().items()]
    (
    WordCloud(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add(series_name="高校专业词云图", data_pair=专业, word_size_range=[10, 100])
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="高校专业词云图", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
        ),
        tooltip_opts=opts.TooltipOpts(is_show=True),
    )
     .render("cloud.html")
)
    with open("cloud.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,g='active',wz=''
    )

@app.route('/h')
def h():
    df_学校=index()[0]
    df_学校_985 = df_学校[df_学校['985'] == '是']
    省份_985 = [i for i in df_学校_985['省份'].value_counts().items()]
    data=[]
    for i in range(len(省份_985)):
        data.append({'value':省份_985[i][1],'name':省份_985[i][0]})
    c = (
    TreeMap(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add("省份", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="985高校分布"))
    .render("tree2.html")
)
    with open("tree2.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,h='active',wz=''
    )

@app.route('/i')
def i():
    df_学校=index()[0]
    df_学校_211 = df_学校[df_学校['211'] == '是']
    省份_211 = [i for i in df_学校_211['省份'].value_counts().items()]
    data=[]
    for i in range(len(省份_211)):
        data.append({'value':省份_211[i][1],'name':省份_211[i][0]})
    c = (
    TreeMap(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add("省份", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="211高校分布"))
    .render("tree3.html")
)   
    with open("tree3.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,i='active',wz=''
    )

@app.route('/j')
def j():
    df_学校=index()[0]
    df_学校_双一流 = df_学校[df_学校['双一流'] == '是']
    省份_双一流 = [i for i in df_学校_双一流['省份'].value_counts().items()]
    data=[]
    for i in range(len(省份_双一流)):
        data.append({'value':省份_双一流[i][1],'name':省份_双一流[i][0]})
    c = (
    TreeMap(init_opts=opts.InitOpts(width="900px", height="700px", bg_color="white"))
    .add("省份", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="双一流高校分布"))
    .render("tree4.html")
)   
    with open("tree4.html", encoding="utf8", mode="r") as f:
            plot_a = "".join(f.readlines())
    return render_template(
    'index.html',rl=plot_a,j='active',wz=''
    )

 
    
if __name__ == '__main__':
    app.run()